package com.hp.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.hp.ssm.entity.Doctor;
import com.hp.ssm.entity.Files;
import com.hp.ssm.entity.Hospital;
import com.hp.ssm.entity.Patient;
import com.hp.ssm.service.FilesService;
import com.hp.ssm.util.ResultJson;
import com.hp.ssm.util.Utils;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 23129
 * 文件管理
 */
@Controller
public class FilesController {

   @Resource
   private FilesService filesService;

    @RequestMapping("/showAll")
    public ModelAndView showAll(HttpServletResponse resp, Integer page, Integer limit,Files files) {
        System.out.println(files);
        ModelAndView mv = new ModelAndView();
        List<Files> list = filesService.showAll(files,page, limit);
        PageInfo<Files> userPageInfo = new PageInfo<Files>(list);
        System.out.println(userPageInfo);
        ResultJson success = ResultJson.success(userPageInfo);
        Utils.returnJson(success, resp);
        return mv;
    }

    @RequestMapping("/chenckPuser")
    public ModelAndView chenckPuser(String puser,HttpServletResponse resp) {
        ModelAndView mv = new ModelAndView();
        Patient patient = filesService.chenckPuser(puser);
        if (patient != null) {
            ResultJson success = ResultJson.success(patient);
            Utils.returnJson(success, resp);
        } else {
            ResultJson error = ResultJson.error();
            Utils.returnJson(error, resp);
        }
        return mv;
    }

    @RequestMapping("/add")
    public ModelAndView add(Files files, HttpServletResponse resp) {
        ModelAndView mv = new ModelAndView();
        System.out.println(files);
        String puser = files.getPatient().getPuser();
        int cid = filesService.cid(puser);
        files.setCid(cid);
        int i = filesService.add(files);
        if (i > 0) {
            ResultJson success = ResultJson.success(i);
            Utils.returnJson(success, resp);
        } else {
            ResultJson error = ResultJson.error();
            Utils.returnJson(error, resp);
        }
        return mv;
    }
    @RequestMapping("/del")
    public ModelAndView del(Integer cid, HttpServletResponse resp) {
        ModelAndView mv = new ModelAndView();
        int i = filesService.del(cid);
        ResultJson success = ResultJson.success(i);
        Utils.returnJson(success, resp);
        return mv;
    }


    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest req) throws UnsupportedEncodingException {
        System.out.println("springmvc文件上传。。。。");
        //获取原始文件名称
        String originalFileName = uploadFile.getOriginalFilename();
        System.out.println(originalFileName);
        //存储文件的文件夹名称
        String upload = req.getSession().getServletContext().getRealPath("upload");
        System.out.println(upload);
        //与目的地建立连接
        File file = new File(upload);
        if(!file.exists()){
            file.mkdirs();
        }
        //获取文件后缀
        String suffix = originalFileName.substring(originalFileName.lastIndexOf(".",originalFileName.length()));
        String filename = upload.concat(File.separator).concat(UUID.randomUUID().toString()).concat(suffix);
        try {
            uploadFile.transferTo(file);
            return originalFileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 文件下载
     * */
    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<byte[]> download(HttpServletRequest req, String filename) {
        System.out.println(filename);
        //文件地址在项目内部的（目的地址信息）
        // String upload = req.getServletContext().getRealPath("upload");
        //目的仓库在项目之外
        String upload = "D:\\files";
        //先拼接具体的位置路径，然后通过file进行建立连接
        File file = new File(upload + File.separator + filename);
        System.out.println(file);
        if (!file.exists()) {//如果不存在文件，直接返回null
            return null;
        }
        try {
            //创建标头文件对象
            HttpHeaders headers = new HttpHeaders();
            //解决乱码问题
            String downloadfile = new String(filename.getBytes(StandardCharsets.UTF_8), "ISO-8859-1");
            //以下载的方式打开文件
            headers.setContentDispositionFormData("attachment", filename);
            //二进制流
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
